package struct.queue.realize;

/**
 * @author: 柒月
 * @date: 2025/5/2 下午5:24
 * @version: 1.0
 */
public class ArrayDeque {

    private final int[] array;
    private int head;
    private int tail;
    private int size;
    private final int capacity;

    public ArrayDeque(int size) {
        capacity = size;
        array = new int[size];
        this.size = 0;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public int size() {
        return size;
    }

    public boolean isFull() {
        return size == capacity;
    }

    public void offerLast(int value) {
        if (isFull()) {
            throw new IllegalStateException("Queue is full");
        }
        if (isEmpty()) {
            head = tail = 0;
            array[0] = value;
        } else {
            tail = tail == capacity - 1 ? 0 : tail + 1;
            array[tail] = value;
        }
        size++;
    }

    public void offerFirst(int value) {
        if (isFull()) {
            throw new IllegalStateException("Queue is full");
        }
        if (isEmpty()) {
            head = tail = 0;
            array[0] = value;
        } else {
            head = head == 0 ? capacity - 1 : head - 1;
            array[head] = value;
        }
        size++;
    }

    public int pollFirst() {
        if (isEmpty()) {
            throw new IllegalStateException("Queue is empty");
        }
        int value = array[head];
        head = head == capacity - 1 ? 0 : head + 1;
        size--;
        return value;
    }

    public int pollLast() {
        if (isEmpty()) {
            throw new IllegalStateException("Queue is empty");
        }
        int value = array[tail];
        tail = tail == 0 ? capacity - 1 : tail - 1;
        size--;
        return value;
    }

    public int peekFirst() {
        if (isEmpty()) {
            throw new IllegalStateException("Queue is empty");
        }
        return array[head];
    }

    public int peekLast() {
        if (isEmpty()) {
            throw new IllegalStateException("Queue is empty");
        }
        return array[tail];
    }

}
